package com.zxl.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

public class downloadFile{
	public static void main(String args[]){
		boolean b = false;
		downloadFile df = new downloadFile();
		b = df.downloadFile("download\\","Foxit Reader.exe");
		System.out.println("b:" + b);
	}

	/** ftp服务器地址 */
	public String ftpHost = "192.168.0.121";
	/** ftp服务器用户名 */
	private String ftpName = "anonymous";
	/** ftp服务器密码 */
	private String ftpPass = "";
	/** ftp根目录 */
	private String ftpDir = "/";
	/** 本地目录 */
	private String localPath = "E:\\";
	public boolean downloadFile(String path, String fileName) {
	
		// 全部路径
		String fullPath = path + fileName;
		FTPClient client = new FTPClient();
		// 超时
		client.setConnectTimeout(30000);
		File dir = new File(localPath + path);
		// 判断此文件夹是否存在
		if (!dir.exists())
			dir.mkdirs();
		try {
			// 连接ftp
			client.connect(ftpHost);
			int replyCode = client.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				client.disconnect();
				return false;
			}
			replyCode = client.getReplyCode();
			if (!FTPReply.isPositiveCompletion(replyCode)) {
				client.quit();
				return false;
			}
			// 登录
			if (client.login(ftpName, ftpPass)) {
				// 以2开头的返回值就会为真
				if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
					client.disconnect();
					System.out.println("连接ftp失败");
				}
				/** ftp server system type */
				FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
				/** server language */
				config.setServerLanguageCode("zh");
				/** server time zone */
				config.setServerTimeZoneId("Asia/Shanghai");
				/** ftp transfer mode in binary */
				client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
				/** receive buffer size */
				client.setReceiveBufferSize(524288);
				client.configure(config);
				client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
				client.setFileType(FTP.BINARY_FILE_TYPE);
				client.changeWorkingDirectory(ftpDir);// 转移到FTP服务器目录
				// 下载到本地
				return client.retrieveFile(ftpDir + fileName, new FileOutputStream(localPath + fullPath));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (client.isConnected()) {
				try {
					client.logout();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
}